package io.wdb.wxapp.util;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 微信小程序支付util
 * @author zeteng
 *
 */
public class WxAppPayUtil {
	private static Logger logger = LoggerFactory.getLogger(WxAppPayUtil.class);

	/**
	 * 统一下单接口
	 * @param body
	 * @param outTradeNo
	 * @param openid
	 * @param totalFee
	 * @return
	 */
	public static String unifiedorder(String body, String outTradeNo, String openid, String totalFee, 
			String appid, String mch_id, String notify_url, String apiKey) {
		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		
		parameters.put("appid", appid);
		parameters.put("mch_id", mch_id);
		parameters.put("nonce_str", PayCommonUtil.createNoncestr());
		parameters.put("body", body);
		parameters.put("out_trade_no", outTradeNo);
		parameters.put("total_fee", totalFee);
		parameters.put("spbill_create_ip", "47.100.117.234");
		parameters.put("notify_url", notify_url);
		parameters.put("trade_type", "JSAPI");
		parameters.put("openid", openid);
		
		String sign = PayCommonUtil.createSign(parameters, apiKey);
		parameters.put("sign", sign);
		
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		String result = CommonUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);

		logger.info("微信支付下单请求返回:{}",result);
		Map<String, String> map = new HashMap<String, String>();
		try {
			map = XMLUtil.doXMLParse(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  // 解析微信返回的信息，以Map形式存储便于取值
		
		return map.get("prepay_id").toString();
	}
}
